package cn.wolfcode.web.controller;

import cn.wolfcode.annotation.PermissionName;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * ClassName RoleController
 * Create by Mike
 * Date 2021/8/1 16:52
 */
@Controller
@RequestMapping("/role")
public class RoleController {


    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @PermissionName("角色查询")
    @RequiresPermissions("role:list")
    public String list(Model model, QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/role/list";
    }

    //去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id, Model model){
        if (id != null){
            //去修改
            model.addAttribute("role",roleService.get(id));
            //直接手动调用权限业务对象的方法从查询此角色对应权限
            model.addAttribute("ownPermission",permissionService.queryByRoleId(id));
        }
        model.addAttribute("permissions",permissionService.listAll());
        return "role/input";//让浏览器重新发一次
       }

    //新增或修改
    @RequestMapping("/saveOrUpdate")
    @PermissionName("角色新增/修改")
    @RequiresPermissions("role:saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] permissionIds){
        if (role.getId() == null){//表示新增
            roleService.save(role,permissionIds);
        }else {//表示修改
            roleService.update(role,permissionIds);
        }
        return "redirect:/role/list";//让浏览器重新发一次
    }

    @RequestMapping("/delete")
    @PermissionName("角色删除")
    @RequiresPermissions("role:delete")
    public String delete(Long id){
        if (id != null){
            roleService.delete(id);
        }
        permissionService.batchDelete(id);
        return "redirect:/role/list";
    }
}
